﻿using System;
using System.Linq;
using System.Web.Mvc;
using MusicStore.WebMVC.Models;

namespace MusicStore.WebMVC.Controllers
{
    [Authorize]
    public class CheckoutController : BaseController
    {
        const string PromoCode = "Free";

        //
        // GET: /Checkout/

        public ActionResult Index()
        {
            return View();
        }

        //get: /Checkout/AddressAndPayment

        public ViewResult AddressAndPayment()
        {
            return View();
        }

        //post: /Checkout/AddressAndPayment

        [HttpPost]
        public ActionResult AddressAndPayment(FormCollection values)
        {
            var order = new Order();
            TryUpdateModel(order);

            try
            {
                if (!string.Equals(values["PromoCode"], PromoCode, StringComparison.OrdinalIgnoreCase))
                {
                    return View(order);
                }
                else
                {
                    order.Username = User.Identity.Name;
                    order.OrderDate = DateTime.Now;

                    //save order
                    db.Orders.Add(order);
                    db.SaveChanges();

                    //process the order
                    var cart = ShoppingCart.GetCart(this.HttpContext);
                    cart.CreateOrder(order);

                    return RedirectToAction("Complete", new { id = order.OrderId });
                }
            }
            catch
            {
                //invalid-redisplay with errors
                return View(order);
            }
        }

        // GET: /Checkout/Complete 

        public ViewResult Complete(int id)
        {
            // Validate customer owns this order 
            bool isValid = db.Orders.Any(
                o => o.OrderId == id &&
                o.Username == User.Identity.Name);

            if (isValid)
            {
                return View(id);
            }
            else
            {
                return View("Error");
            }
        } 
    }
}